package com.zut.rabbitmq;

import com.rabbitmq.client.Channel;
import com.zut.Conf.RabbitmqConfig;
import com.zut.Service.HttpJudge;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;

/**
 * Rabbitmq消费者，定义三个消费者
 */
@Component
@Slf4j
public class acceptMsg {

    @Autowired
    private HttpJudge httpJudge;

    @RabbitListener(queues =RabbitmqConfig.QUEUE_NAME)
    public void acceptMsgOne(String obj,Message msg, Channel channel){

        extracted(obj,msg, channel);


    }
    @RabbitListener(queues =RabbitmqConfig.QUEUE_NAME)
    public void acceptMsgTwo(String obj,Message msg, Channel channel){

        extracted(obj,msg, channel);
    }

    @RabbitListener(queues =RabbitmqConfig.QUEUE_NAME)
    public void acceptMsgThree(String obj,Message msg, Channel channel){

        extracted(obj,msg, channel);
    }

    private void extracted(String obj,Message msg, Channel channel) {
        long deliverTag = msg.getMessageProperties().getDeliveryTag();
        try {
            //业务逻辑代码...
            httpJudge.GoJudge(obj);
            //消费成功，确认消息
            channel.basicAck(deliverTag, true);
        }catch (Exception e){
            //拒绝消息,为true会重新放回队列（自定义拒绝规则，比如：redis计数，消费5次后依然报错失败则拒绝）
            try {
                channel.basicReject(deliverTag, false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            try {
                //nack返回false，并重新回到队列
                channel.basicNack(deliverTag, false, true);
            } catch (IOException ioException) {

                log.error("重新放入队列失败，失败原因:{}",e.getMessage(),e);
            }
            log.error("TopicConsumer消费者出错,mq参数:{}，错误信息：{}",e.getMessage(),e);


        }
    }


}
